package com.shawn.spring.boot.jpa.run;

import com.shawn.spring.boot.jpa.entity.User;
import com.shawn.spring.boot.jpa.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author shawn
 * @since 2020/8/31
 */
@Component
@Slf4j
public class JpaRunner implements ApplicationRunner {

  @Autowired private UserService userService;

  @Override
  public void run(ApplicationArguments args) throws Exception {
    register();
    errorRegister();
  }

  @Transactional
  public void register() {
    User shawn =
        User.builder()
            .email("1111@qq.com")
            .mobile("12345678901")
            .password("123456")
            .salt("12345")
            .username("shawn")
            .isDeleted(0)
            .build();
    try {
      userService.insertThenRollback(shawn);
    } catch (Exception e) {
      userService.findAll().forEach(user -> log.info(user.toString()));
    }
  }

  @Transactional
  public void errorRegister() {
    User error =
        User.builder()
            .email("1111@qq.com")
            .mobile("12345678901")
            .password("error")
            .salt("12345")
            .username("error")
            .isDeleted(0)
            .build();
    try {
      userService.invokeInsertThenRollback(error);
    } catch (RuntimeException e) {
      userService.findAll().forEach(user -> log.info(user.toString()));
    }
  }
}
